# -*- coding: utf-8 -*-
from datetime import datetime
import os
from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template.context import RequestContext
from django.views.generic.list import ListView
from main.models import Employee, Unit, CurrentSite, XLS_templates
from vacations.models import Vacation
import xlrd
from xlutils.copy import copy
from xlutils.filter import BaseReader, BaseFilter, process, BaseWriter
from xlwt.Style import easyxf

Month_list = (u'Январь',
              u'Февраль',
              u'Март',
              u'Апрель',
              u'Май',
              u'Июнь',
              u'Июль',
              u'Август',
              u'Сентябрь',
              u'Октябрь',
              u'Ноябрь',
              u'Декабрь',
              )


def edit_vacations(request, u_id):
 if CurrentSite.objects.all()[0].vac_access:
    u= get_object_or_404(Unit, pk=u_id)
    if u in request.user.get_profile().unit_access.all() or request.user.is_superuser:
        employee_list = Employee.objects.filter(actual_unit=u)
        next_year = datetime.now().year+1
        if request.POST:
            workers = request.POST.getlist(u'worker')
            otpusk1 = request.POST.getlist(u'a_vac1')
            otpusk2 = request.POST.getlist(u'a_vac2')
            zipped = zip(workers, otpusk1, otpusk2)
            if request.user.is_superuser:
                for workers, otp1, otp2 in zipped:
                        obj, created = Vacation.objects.get_or_create(employee_id=workers, year = next_year, \
                            defaults={'a_vacation1':otp1, 'a_vacation2':otp2, "a_vac_time":datetime.now()})
                        if not created and (otp1 != obj.a_vacation1 or otp2 != obj.a_vacation2):
                            obj.a_vacation1=otp1
                            obj.a_vacation2=otp2
                            obj.a_vac_time=datetime.now()
                            obj.save()

            else:
                for workers, otp1, otp2 in zipped:
                        obj, created = Vacation.objects.get_or_create(employee_id=workers, year = next_year, \
                            defaults={'m_vacation1':otp1, 'm_vacation2':otp2, "m_vac_time":datetime.now()})
                        if not created and (otp1 != obj.m_vacation1 or otp2 != obj.m_vacation2):
                            obj.m_vacation1=otp1
                            obj.m_vacation2=otp2
                            obj.m_vac_time=datetime.now()
                            obj.save()


        vac_list = Vacation.objects.filter(employee__actual_unit=u, year=next_year)

        for item in employee_list:
            if item.id not in vac_list.values_list('employee', flat=True):
                e = Vacation(employee=item, year=datetime.now().year+1)
                e.save()
        return render_to_response('vacations/edit.html', {'year':next_year, 'unit':u, 'm_list':Month_list, 'vac_list':Vacation.objects.filter(employee__actual_unit=u, year=next_year)}, context_instance=RequestContext(request))
    else:
        raise Http404
 else:
    raise Http404



class VacList(ListView):
    template_name = 'vacations/vac_emp.html'
    def get_queryset(self):
        if self.request.user.is_superuser or Employee.objects.get(id=self.kwargs.get('pk', None)).actual_unit in self.request.user.get_profile().unit_access.all():
            return Vacation.objects.filter(employee__id=self.kwargs.get('pk', None)).order_by('year')
        else:
            raise PermissionDenied

    def get_context_data(self, **kwargs):
        context = super(VacList, self).get_context_data(**kwargs)
        context['m_list'] = Month_list
        context['years'] = [year for year in range(2005, datetime.now().year+2)]
        context['emp'] = self.kwargs.get('pk', None)
        return context



def add_update(request, pk):
    if request.user.is_superuser:
        if request.POST and request.POST['year']:
            obj, created = Vacation.objects.get_or_create(employee_id=pk, year = request.POST['year'], \
                            defaults={'a_vacation1':request.POST['vac1'], 'a_vacation2':request.POST['vac2'], "a_vac_time":datetime.now()})
            if not created:
                 obj.a_vacation1=request.POST['vac1']
                 obj.a_vacation2=request.POST['vac2']
                 obj.a_vac_time=datetime.now()
                 obj.save()
        return redirect('vacations_by_employee', pk=pk)
    else:
        raise Http404

def add_access(request):
    if request.user.is_superuser:
        a = CurrentSite.objects.all()[0]
        if a.vac_access:
            a.vac_access = False
            a.save()
        else:
            a.vac_access = True
            a.save()
        return redirect('v_start')
    else:
        raise Http404

def vac_start(request):
    a=None
    year = datetime.now().year
    default = year+1
    a = CurrentSite.objects.all()[0]
    y_list = [year for year in range(2005, datetime.now().year+2)]
    return render_to_response('vacations/start.html', {'access':a.vac_access, "year":year, "n_year":year+1, 'y_list':y_list , "default":default}, context_instance=RequestContext(request))


def vac_view(request, u_id, year):
    u= get_object_or_404(Unit, pk=u_id)
    if u in request.user.get_profile().unit_access.all() or request.user.is_superuser:
        employee_list = Employee.objects.filter(actual_unit=u, dismissed=False)
        if int(year)+1 > datetime.now().year+2:
            next_year = None
        else:
            next_year = int(year)+1

        if int(year)-1 < 2005:
            prev_year = None
        else:
            prev_year = int(year)-1
        year_now = year
        vac_list = Vacation.objects.filter(employee__actual_unit = u_id, year=year)
        return render_to_response('vacations/list.html',locals(), context_instance=RequestContext(request))
    else:
        raise Http404



class Reader(BaseReader):

    def __init__(self, obj):
        self.obj = obj
    def get_filepaths(self):
        return [os.path.abspath(self.obj.file.path)]

class Writer(BaseWriter):
    def get_stream(self,filename):
        return file(filename,'wb')

class Filter(BaseFilter):
    def workbook(self,rdbook,wtbook_name):
        self.next.workbook(rdbook,'temp.xls')

def excel_vacations(request,arg):
    if request.POST:
        if arg == 'rsis':
            lst = Vacation.objects.filter(employee__worker_or_rsis=u"R", year=request.POST["year"], employee__dismissed=False)
            stroka = u'График отпусков РСиС на %s год.' % request.POST['year']
            who = "РСиС"
        elif arg == 'workers':
            lst = Vacation.objects.filter(employee__worker_or_rsis__startswith=u"W", year=request.POST["year"], employee__dismissed=False)
            stroka = u'График отпусков рабочих на %s год.' % request.POST['year']
            who = "Рабочих"
        else:
            raise Http404()

        if not request.user.is_superuser:
            raise PermissionDenied

        objecd = XLS_templates.objects.get(name=u"R_V")
        process(Reader(objecd),Filter(), Writer())
        rb = xlrd.open_workbook('temp.xls',on_demand=True,formatting_info=True)
        wb = copy(rb)

        sheet = wb.get_sheet(0)
        sheet1 = wb.get_sheet(1)
        sheet.write(0, 0, stroka,easyxf('font: bold True, height 300, name Arial;' "align: horiz centre, vert centre;"))
        sheet1.write(3, 1, u"По месяцам:",easyxf('font: height 180, name Arial;' "align: horiz left, vert centre"))
        sheet.normal_magn=80
        q=0
        a=4
        r = 2
        c = 0
        cnt = 1
        max=1

        for mon in Month_list:
            sheet.write_merge(r, r, c, c+2, mon,easyxf('font: bold True, height 160, name Arial;' "align: horiz centre, vert centre;" "borders: left thin, right thin,\
                    top thin, bottom thin;"))
            for vac in lst:
                if vac.a_vacation1==mon or vac.a_vacation2==mon:
                    q = q+1
                    fio = u"%s.%s" % (cnt, vac.employee.__unicode__())
                    if vac.employee.vacation_privilege:
                        sheet.write(r+cnt, c, fio,easyxf('font: bold True, height 160, name Arial;' "align: horiz left, vert centre;" "borders: left thin, bottom thin;"))
                    else:
                        sheet.write(r+cnt, c, fio,easyxf('font: height 160, name Arial;' "align: horiz left, vert centre;" "borders: left thin, bottom thin;"))
                    if vac.a_vacation1 and vac.a_vacation2:
                        sheet.write(r+cnt, c+1, u"1/2",easyxf('font: height 160, name Arial;' "align: horiz centre, vert centre;" "borders: bottom thin;"))
                    else:
                        sheet.write(r+cnt, c+1, "",easyxf('font: height 160, name Arial;' "align: horiz centre, vert centre;" "borders: bottom thin;"))
                    sheet.write(r+cnt, c+2, vac.employee.tabel_number[2:],easyxf('font: height 160, name Arial;' "align: horiz centre, vert centre;" "borders: right thin, bottom thin;"))
                    cnt=cnt+1

            sheet1.write(a, 1, mon,easyxf('font: height 180, name Arial;' "align: horiz left, vert centre"))
            sheet1.write(a, 2, q,easyxf('font: height 180, name Arial;' "align: horiz left, vert centre"))
            q=0
            a=a+1

            if max < cnt:
                max=cnt
            cnt=1
            if mon == u'Июнь':
                c=0
                r=max+3
                max=0
            else:
                c=c+4
        a = CurrentSite.objects.all()[0]


        sheet.write(r+max+2, 5, u"Начальник отдела",easyxf('font: height 180, name Arial;' "align: horiz left, vert centre"))
        sheet.write(r+max+2, 10, a.chief,easyxf('font: height 180, name Arial;' "align: horiz left, vert centre"))
        sheet.write(r+max+4, 5, u"Председатель цехкома",easyxf('font: height 180, name Arial;' "align: horiz left, vert centre"))
        sheet.write(r+max+4, 10, a.chairman,easyxf('font: height 180, name Arial;' "align: horiz left, vert centre"))

        sheet1.write(1, 1, u"Всего сотрудников:",easyxf('font: height 180, name Arial;' "align: horiz left, vert centre"))
        sheet1.write(1, 2, lst.count(),easyxf('font: height 180, name Arial;' "align: horiz left, vert centre"))

        fname = "Отпуска %s на %s год.xls" % ( str(who),str(datetime.now().year+1))
        response = HttpResponse(mimetype="application/vnd.ms-excel")
        response['Content-Disposition'] = 'attachment; filename=%s' % fname

        sheet.fit_num_pages = 1
        sheet.fit_height_to_pages = 0
        sheet.fit_width_to_pages = 1
        sheet.portrait = 0
        wb.save(response)

        return response
    else:
        raise Http404
